package com.darren.euc.action.member;

import com.alibaba.fastjson.JSON;
import com.darren.euc.action.FunctionAction;
import com.darren.euc.action.MemberAction;
import com.darren.euc.entity.*;
import com.darren.euc.service.*;
import com.darren.euc.util.Constant;
import com.darren.euc.util.ExcelToJson;
import com.darren.euc.util.FileUploadUtils;
import com.darren.euc.util.PropertyConfigurer;
import com.google.common.collect.Lists;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员中心登录
 * Created by yanglisheng on 18/3/24.
 */
@Controller
@RequestMapping("/center/member")
public class CenterMemberAction {
    @Autowired
    private FunctionService functionService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ClientService clientService;

    @Autowired
    private ExtensionService extensionService;

    @ResponseBody
    @RequestMapping(value = "/extension/list")//,method = RequestMethod.POST)
    public List<Extension> getAllEnabelExtensions(HttpServletRequest request,HttpServletResponse response) {
        List<Extension> extensions = extensionService.getAllEnableExtensions();
        return extensions;
    }

    /**
     * 会员登录页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {

        return "member/login";
    }

    /**
     * 会员主页
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/page")
    public String getAllFunctions(HttpServletRequest request,HttpServletResponse response) {

        return "member/application";
    }


    @ResponseBody
    @RequestMapping(value = "/function/list",method = RequestMethod.POST)
    public JSONArray getFunctionList(HttpServletRequest request, HttpServletResponse response) {
        List<Function> functions = new ArrayList<Function>();
        Member user = (Member) request.getAttribute("member");
        if(user != null){
            functions = functionService.getMemberCenterFunctions();
        }
        JSONArray functonArray = FunctionAction.constructFunctionTree(functions,0);
        return functonArray;
    }
    /**
     * 添加部门
     */
    @RequestMapping(value = "/addDept",method = RequestMethod.POST)
    @ResponseBody
    public ResponseJSON addDept(@RequestBody DeptVO dept, HttpServletRequest request, HttpServletResponse response){
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        try{
            dept.setClientId(user.getClientId());
            Dept dep = deptService.addDept(dept);
            return new ResponseJSON().set(Constant.STATUS_SUCCESS,"操作成功",dep);
        }catch(Exception e){
            e.printStackTrace();
            return new ResponseJSON().set(-1,e.getMessage(),null);
        }
    }
    /**
     * 删除部门
     */
    @RequestMapping(value = "/delDept",method = RequestMethod.GET)
    @ResponseBody
    public ResponseJSON delDept(@RequestParam  int id, HttpServletRequest request, HttpServletResponse response){
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        try{
            Boolean dep = deptService.deleteDeptById(id);
            return new ResponseJSON().set(Constant.STATUS_SUCCESS,"操作成功",dep);
        }catch(Exception e){
            e.printStackTrace();
            return new ResponseJSON().set(-1,e.getMessage(),null);
        }
    }

    /**
     * 部门列表
     */
    @ResponseBody
    @RequestMapping(value = "/list")//,method = RequestMethod.POST)
    public List<Dept> getAll(HttpServletRequest request,HttpServletResponse response) {
        Member user = (Member) request.getAttribute("member");
        List<Dept> clients = deptService.getAll(user.getClientId());
        return clients;
    }
    /**
     * 管理员工，新增修改员工
     */
    /**
     * 保存会员
     * @param member
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value= "/add",method = RequestMethod.POST)
    public ResponseJSON saveMember(@RequestBody Member member, HttpServletResponse response, HttpServletRequest request){
        //表单提交
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        member.setCreatedBy(user.getName());
        member.setLastModifyBy(user.getName());
        Member persistent = null;
        try {
            //设置相关spaceid，clientid
            member.setClientId(user.getClientId());
            member.setSpaceId(user.getSpaceId());
            persistent = memberService.saveMember(member);
            if(persistent != null){
                return  ResponseJSON.defaultSuccessResponse();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseJSON().set(-1,e.getMessage(),null);
        }

        return ResponseJSON.defaultFailedResponse();
    }


    /**
     * 批量导入
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/batchImport",method = RequestMethod.GET)
    public ResponseJSON batchImport(@RequestParam("file_path") String file_path,
                                    HttpServletRequest request) throws IOException {
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        ExcelToJson excelToJson = new ExcelToJson();
        String jsonResult = null;
        try {
            jsonResult = excelToJson.doExcelToJson(file_path, 0, 0);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseJSON(-1,"导入失败",null);
        }
        List<MemberMould> memberMoulds = JSON.parseArray(jsonResult, MemberMould.class);
        List<Member> members = Lists.newArrayList();
        User realuser = new User();
        realuser .setUserName(user.getName());
        memberMoulds.forEach(memberMould -> members.add(MemberAction.memberMould2Member(memberMould,user.getClientId(),user.getSpaceId(),realuser)));
        try{
            memberService.saveMembers(members);
        }catch (Exception e){
            return new ResponseJSON().set(-1,e.getMessage());
        }
        return ResponseJSON.defaultSuccessResponse();
    }


    /**
     * 上传logo
     */
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseJSON uploadPhoto(MultipartFile file,HttpServletRequest request) throws IOException {
        // String path = request.getScheme()+"://"+request.getRemoteHost()+":"+request.getServerPort();
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        String path = PropertyConfigurer.getPropertiesStr("server.ip")+":"+request.getServerPort();
        String headUrl = request.getSession().getServletContext().getContextPath()+"/"+FileUploadUtils.uploadFile(file, request,"images/clientLogo");
        return ResponseJSON.defaultSuccessResponse(path + headUrl);
    }
    @ResponseBody
    @RequestMapping(value = "/uploadWithMemberId",method = RequestMethod.POST)
    public ResponseJSON uploadPhotoWithId(@RequestParam MultipartFile file, @RequestParam Integer memberId,HttpServletRequest request) throws IOException {
        Member member = (Member) request.getAttribute("member");
        if(member == null){
            return new ResponseJSON().set(-2, "操作失败，未登录");
        }
        String path = /*request.getScheme()+"://"+ */PropertyConfigurer.getPropertiesStr("server.ip")+":"+request.getServerPort();
        String headUrl = request.getSession().getServletContext().getContextPath()+"/"+ FileUploadUtils.uploadFile(file, request,"images");
        try{
            String picUrl = path + headUrl;
            Member db = memberService.findByMemberId(memberId);
            memberService.updateHead(picUrl,db);
            return ResponseJSON.defaultSuccessResponse(picUrl);
        }catch(Exception e){
            return new ResponseJSON().set(-2, e.getMessage());

        }
    }
    /**
     * 修改client
     * 只要不为空的数据
     */
    @ResponseBody
    @RequestMapping(value = "/updateClientInfos",method = RequestMethod.POST)
    public ResponseJSON saveClient(@RequestBody Client client,HttpServletRequest request,HttpServletResponse response) {
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        if(user.getClientId() == null || user.getClientId()<1){
            return new ResponseJSON().set(-1,"当前操作人员没有所属客户",null);
        }
        client.setId(user.getClientId());
        ResponseJSON responseJson = new ResponseJSON();
        try {
            client = clientService.update(client);
            responseJson.setStatus(0);
            responseJson.setMessage("更新成功！");
        } catch (Exception ex) {
            responseJson.setStatus(-1);
            responseJson.setMessage("更新失败！");
        }
        responseJson.setData(client);
        System.out.println("==============================================================");
        System.out.println(responseJson.toString());
        System.out.println("==============================================================");
        return responseJson;
    }
    @ResponseBody
    @RequestMapping(value = "/getClientInfos",method = RequestMethod.GET)
    public ResponseJSON clientInfos(HttpServletRequest request,HttpServletResponse response){
        Member user = (Member) request.getAttribute("member");
        if(user == null || user.getIsAdmin()!= 1){
            return new ResponseJSON().set(-1,"只有管理员有操作权限",null);
        }
        if(user.getClientId() == null)
            return new ResponseJSON().set(-1,"该用户还没有所属的客户");

        Clue client = clientService.findByClientId(user.getClientId());

        if(client != null && client.getClient()!= null){
            return new ResponseJSON().set(-1,"获取成功",client.getClient());
        }
        return ResponseJSON.defaultFailedResponse();
    }
}
